import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useAuthState } from 'react-firebase-hooks/auth';
import {
  doc,
  getDoc,
  updateDoc,
  deleteDoc,
  increment,
  arrayUnion,
  arrayRemove,
} from 'firebase/firestore';
import { db, auth } from '../services/firebase';
import { Copywriting, User } from '../types';

const CopywritingDetail = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [user] = useAuthState(auth);
  const [copywriting, setCopywriting] = useState<Copywriting | null>(null);
  const [author, setAuthor] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isLiked, setIsLiked] = useState(false);
  const [isFavorited, setIsFavorited] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  useEffect(() => {
    const fetchCopywriting = async () => {
      if (!id) return;

      try {
        const docRef = doc(db, 'copywriting', id);
        const docSnap = await getDoc(docRef);

        if (docSnap.exists()) {
          const data = { id: docSnap.id, ...docSnap.data() } as Copywriting;
          setCopywriting(data);

          // 获取作者信息
          const authorRef = doc(db, 'users', data.authorId);
          const authorSnap = await getDoc(authorRef);
          if (authorSnap.exists()) {
            setAuthor({ uid: authorSnap.id, ...authorSnap.data() } as User);
          }

          // 检查当前用户是否已点赞和收藏
          if (user) {
            const userRef = doc(db, 'users', user.uid);
            const userSnap = await getDoc(userRef);
            if (userSnap.exists()) {
              const userData = userSnap.data() as User;
              setIsLiked(userData.likes?.includes(id) || false);
              setIsFavorited(userData.favorites?.includes(id) || false);
            }
          }
        } else {
          setError('文案不存在');
        }
      } catch (err) {
        console.error('Error fetching copywriting:', err);
        setError('加载失败');
      } finally {
        setLoading(false);
      }
    };

    fetchCopywriting();
  }, [id, user]);

  const handleLike = async () => {
    if (!user || !copywriting) return;

    try {
      const userRef = doc(db, 'users', user.uid);
      const copywritingRef = doc(db, 'copywriting', copywriting.id);

      if (isLiked) {
        await updateDoc(userRef, {
          likes: arrayRemove(copywriting.id),
        });
        await updateDoc(copywritingRef, {
          likes: increment(-1),
        });
      } else {
        await updateDoc(userRef, {
          likes: arrayUnion(copywriting.id),
        });
        await updateDoc(copywritingRef, {
          likes: increment(1),
        });
      }

      setIsLiked(!isLiked);
      setCopywriting((prev) =>
        prev
          ? { ...prev, likes: prev.likes + (isLiked ? -1 : 1) }
          : null
      );
    } catch (err) {
      console.error('Error updating like:', err);
    }
  };

  const handleFavorite = async () => {
    if (!user || !copywriting) return;

    try {
      const userRef = doc(db, 'users', user.uid);
      const copywritingRef = doc(db, 'copywriting', copywriting.id);

      if (isFavorited) {
        await updateDoc(userRef, {
          favorites: arrayRemove(copywriting.id),
        });
        await updateDoc(copywritingRef, {
          favorites: increment(-1),
        });
      } else {
        await updateDoc(userRef, {
          favorites: arrayUnion(copywriting.id),
        });
        await updateDoc(copywritingRef, {
          favorites: increment(1),
        });
      }

      setIsFavorited(!isFavorited);
      setCopywriting((prev) =>
        prev
          ? { ...prev, favorites: prev.favorites + (isFavorited ? -1 : 1) }
          : null
      );
    } catch (err) {
      console.error('Error updating favorite:', err);
    }
  };

  const handleDelete = async () => {
    if (!copywriting || !user || user.uid !== copywriting.authorId) return;

    try {
      await deleteDoc(doc(db, 'copywriting', copywriting.id));
      navigate('/');
    } catch (err) {
      console.error('Error deleting copywriting:', err);
      setError('删除失败');
    }
  };

  const handleShare = () => {
    const url = window.location.href;
    navigator.clipboard.writeText(url).then(() => {
      alert('链接已复制到剪贴板');
    });
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="text-lg">加载中...</div>
      </div>
    );
  }

  if (error || !copywriting) {
    return (
      <div className="max-w-3xl mx-auto px-4 py-8">
        <div className="text-red-600 text-center">{error || '文案不存在'}</div>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto px-4 py-8">
      {/* 作者信息 */}
      <div className="mb-8 flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <img
            src={author?.photoURL || '/default-avatar.png'}
            alt={author?.displayName}
            className="w-12 h-12 rounded-full"
          />
          <div>
            <Link
              to={`/profile/${author?.uid}`}
              className="text-lg font-medium text-gray-900 hover:text-blue-600"
            >
              {author?.displayName}
            </Link>
            <div className="text-sm text-gray-500">
              {new Date(copywriting.createdAt.toDate()).toLocaleDateString()}
            </div>
          </div>
        </div>
        {user?.uid === copywriting.authorId && (
          <div className="flex space-x-2">
            <Link
              to={`/edit/${copywriting.id}`}
              className="inline-flex items-center px-3 py-1.5 border border-gray-300 text-sm font-medium rounded text-gray-700 bg-white hover:bg-gray-50"
            >
              编辑
            </Link>
            <button
              onClick={() => setShowDeleteConfirm(true)}
              className="inline-flex items-center px-3 py-1.5 border border-red-300 text-sm font-medium rounded text-red-700 bg-white hover:bg-red-50"
            >
              删除
            </button>
          </div>
        )}
      </div>

      {/* 文案内容 */}
      <article className="prose max-w-none">
        <h1 className="text-3xl font-bold text-gray-900 mb-4">
          {copywriting.title}
        </h1>
        <div className="whitespace-pre-wrap text-gray-800">
          {copywriting.content}
        </div>
      </article>

      {/* 标签 */}
      <div className="mt-6 flex flex-wrap gap-2">
        {copywriting.tags.map((tag) => (
          <span
            key={tag}
            className="inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium bg-blue-100 text-blue-800"
          >
            {tag}
          </span>
        ))}
      </div>

      {/* 来源 */}
      {copywriting.source && (
        <div className="mt-4 text-sm text-gray-500">
          来源：{copywriting.source}
        </div>
      )}

      {/* 交互按钮 */}
      <div className="mt-8 flex items-center justify-between border-t border-gray-200 pt-4">
        <div className="flex space-x-4">
          <button
            onClick={handleLike}
            className={`flex items-center space-x-1 px-3 py-1.5 rounded-md ${
              isLiked
                ? 'text-red-600 bg-red-50'
                : 'text-gray-600 hover:text-red-600 hover:bg-red-50'
            }`}
          >
            <svg
              className="w-5 h-5"
              fill={isLiked ? 'currentColor' : 'none'}
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
              />
            </svg>
            <span>{copywriting.likes || 0}</span>
          </button>
          <button
            onClick={handleFavorite}
            className={`flex items-center space-x-1 px-3 py-1.5 rounded-md ${
              isFavorited
                ? 'text-yellow-600 bg-yellow-50'
                : 'text-gray-600 hover:text-yellow-600 hover:bg-yellow-50'
            }`}
          >
            <svg
              className="w-5 h-5"
              fill={isFavorited ? 'currentColor' : 'none'}
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"
              />
            </svg>
            <span>{copywriting.favorites || 0}</span>
          </button>
        </div>
        <button
          onClick={handleShare}
          className="inline-flex items-center px-3 py-1.5 border border-gray-300 text-sm font-medium rounded text-gray-700 bg-white hover:bg-gray-50"
        >
          分享
        </button>
      </div>

      {/* 删除确认对话框 */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg p-6 max-w-sm w-full">
            <h3 className="text-lg font-medium text-gray-900 mb-4">确认删除</h3>
            <p className="text-gray-500 mb-6">
              确定要删除这篇文案吗？此操作无法撤销。
            </p>
            <div className="flex justify-end space-x-4">
              <button
                onClick={() => setShowDeleteConfirm(false)}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
              >
                取消
              </button>
              <button
                onClick={handleDelete}
                className="px-4 py-2 text-sm font-medium text-white bg-red-600 border border-transparent rounded-md hover:bg-red-700"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default CopywritingDetail;
